package com.runnirr.doodles;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import com.runnirr.doodles.R;
import com.runnirr.doodles.AsyncOperations.LoadDoodleImageAsync;
import com.runnirr.doodles.Database.DataManagementHelper;
import com.runnirr.doodles.Helpers.DoodleData;
import com.runnirr.doodles.Helpers.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

public class DoodleDetails extends Activity {

	private DoodleData currentDoodle;
	
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.doodle_detail_layout);
		
		if (Utils.isApi11Plus()){
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
		
		getDoodleFields();
		populateDisplay();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case android.R.id.home:
	            // This is called when the Home (Up) button is pressed
	            // in the Action Bar.
	            Intent parentActivityIntent = new Intent(this, DoodleList.class);
	            parentActivityIntent.addFlags(
	                    Intent.FLAG_ACTIVITY_CLEAR_TOP |
	                    Intent.FLAG_ACTIVITY_NEW_TASK);
	            parentActivityIntent.putExtra("year", currentDoodle.year);
	            parentActivityIntent.putExtra("month", currentDoodle.month);
	            startActivity(parentActivityIntent);
	            finish();
	            return true;
	    }
	    return super.onOptionsItemSelected(item);
	}


	private void populateDisplay() {
		populateTitle();
		populateDate();
		populateImage();
		populateDescription();
	}

	private void populateTitle() {
		//Title
		setTitle(currentDoodle.title);
	}

	private void populateDate() {
		// Date
		TextView detailDate = (TextView) findViewById(R.id.doodleDetailDate);
		SimpleDateFormat sdf = new SimpleDateFormat("MMM d yyyy");
		sdf.setTimeZone(TimeZone.getTimeZone(TimeZone.getAvailableIDs(0)[0]));
		
		detailDate.setText(sdf.format(currentDoodle.startTime));
	}

	private void populateImage() {
		//Image
		ImageView detailImage = (ImageView) findViewById(R.id.doodleDetailImage);
		DataManagementHelper dmh = new DataManagementHelper(this);
		detailImage.setOnClickListener(imageClickListener);
		
		byte[] image = dmh.selectDoodleImageFromStorage(currentDoodle.ID);
		if (image.length > 0){
			//Load from storage
			System.out.println("Image available in local storage");
			Bitmap bmp = getImageFromByteArray(image);
			detailImage.setImageBitmap(bmp);
			if(detailImage.getVisibility() != View.VISIBLE){
				detailImage.setVisibility(View.VISIBLE);
			}
			return;
		}
		// Fetch from the tubes
		System.out.println("Fetching image from the internet");
		
		AsyncTask<String, Void, Bitmap> imageTask = new LoadDoodleImageAsync().execute(currentDoodle.image);
		
		try {
			Bitmap bmp = imageTask.get();
			detailImage.setImageBitmap(bmp);
			dmh.insertImageToStorage(getByteArrayFromImage(bmp), currentDoodle.ID);
			if(detailImage.getVisibility() != View.VISIBLE){
				detailImage.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			detailImage.setVisibility(View.GONE);
		} 
		
		
	}
	
	private void populateDescription() {
		//Description
		WebView detailDesc = (WebView) findViewById(R.id.doodleDetailDescription);
		if (currentDoodle.text.length() <= 0){
			detailDesc.setVisibility(View.GONE);
		}else{
			detailDesc.loadDataWithBaseURL("http://www.google.com", currentDoodle.text, "text/html", "UTF-8", null);
			detailDesc.setVisibility(View.VISIBLE);
		}
	}
	

	private void getDoodleFields() {
		this.currentDoodle= (DoodleData) getIntent().getSerializableExtra("doodle");
	}
	
	private byte[] getByteArrayFromImage(Bitmap bmp){
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
		return stream.toByteArray();
	}
	
	private Bitmap getImageFromByteArray(byte[] data){
		return BitmapFactory.decodeByteArray(data , 0, data.length);
	}
	
	OnClickListener imageClickListener = new OnClickListener(){
		@Override
		public void onClick(View arg0) {
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(currentDoodle.url)));
		}
	};
	
}
